package com.playball.lottery.frm.yhzx;

import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Html;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.playball.lottery.R;
import com.playball.lottery.ApplicationData;
import com.playball.lottery.base.BaseActivity;
import com.playball.lottery.customview.ShowTipDialog;
import com.playball.lottery.eventmanger.EventManager;
import com.playball.lottery.eventmanger.EventType;
import com.playball.lottery.frm.AnnouncementActivity;
import com.playball.lottery.nt.GetRequestParams;
import com.playball.lottery.util.LotConstants;


public class JddRegisterActivity extends BaseActivity implements LotConstants {

	private static final String TAG = "JddRegisterActivity";
	TextView tv_title;
	private TextView btn_title_left;
	private TextView btn_title_right;
	private TextView btn_bottom_left;
	private TextView btn_bottom_right;

	private Button btn_commit;
	private EditText et_userName,et_user_cmdName;
	private EditText et_userPassword;
	private EditText et_userConfirmPassword;
	private CheckBox cb_anoucement_choice;
	private TextView tv_anoucement;
	private String userName;
	private String userPwd;
	private ShowTipDialog showdialog = new ShowTipDialog();

	private SharedPreferences sp;
	private String RegisterWay="";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		Log.d("JddRegisterActivity", "->onCreate");
		super.onCreate(savedInstanceState);
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.ui_new_register_layout);

		//注册接收来源
		Intent way=this.getIntent();
		RegisterWay=way.getSerializableExtra("LoginFragment").toString();
		
		sp = this.getSharedPreferences("userNamesFile", Activity.MODE_PRIVATE);

		tv_title = (TextView) findViewById(R.id.top_title_info);
		btn_title_left = (TextView) findViewById(R.id.top_title_back);
		btn_title_right = (TextView) findViewById(R.id.top_title_right_btn);
		// btn_bottom_left = (TextView) findViewById(R.id.bottom_left_btn);
		// btn_bottom_right = (TextView) findViewById(R.id.bottom_right_btn);
		btn_commit = (Button) findViewById(R.id.btn_commit);
		et_userName = (EditText) findViewById(R.id.et_user_name);
		et_user_cmdName = (EditText) findViewById(R.id.et_user_cmdName);
		et_userPassword = (EditText) findViewById(R.id.et_password);
		et_userConfirmPassword = (EditText) findViewById(R.id.et_confirm_password);
		cb_anoucement_choice = (CheckBox) findViewById(R.id.cb_announcement_choice);
		tv_anoucement = (TextView) findViewById(R.id.tv_announcement);
		tv_anoucement.setText(Html.fromHtml("<u>我已年满18周岁并且同意《服务条款》</u>"));
		tv_title.setText("注册账户");
		// btn_title_left.setVisibility(View.INVISIBLE);
		btn_title_right.setVisibility(View.INVISIBLE);
		// btn_bottom_right.setVisibility(View.INVISIBLE);
		// btn_bottom_left.setBackgroundResource(R.drawable.login_set_btn_bg);

		// 返回
		btn_title_left.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				JddRegisterActivity.this.finish();
			}
		});

		btn_commit.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				try {

					// close keyboard
					InputMethodManager inputmanger = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
					inputmanger.hideSoftInputFromWindow(btn_commit.getWindowToken(), 0);
					if (cb_anoucement_choice.isChecked() == false) {
						Toast.makeText(JddRegisterActivity.this, R.string.lottery_terms_of_service, Toast.LENGTH_SHORT)
								.show();
					} else if (et_userName.getText().toString().equals("")) {
						Toast.makeText(JddRegisterActivity.this, R.string.user_name_cannot_be_empty, Toast.LENGTH_SHORT)
								.show();
					} else if (et_userPassword.getText().toString().equals("")) {
						Toast.makeText(JddRegisterActivity.this, R.string.password_cannot_be_empty, Toast.LENGTH_SHORT)
								.show();
					} else if (et_userConfirmPassword.getText().toString().equals("")) {
						Toast.makeText(JddRegisterActivity.this, R.string.confirm_password_cannot_be_empty,
								Toast.LENGTH_SHORT).show();
					} else if (!et_userPassword.getText().toString()
							.equals(et_userConfirmPassword.getText().toString())) {
						Toast.makeText(JddRegisterActivity.this, R.string.password_and_confirm_password_no_match,
								Toast.LENGTH_SHORT).show();
					} else if (et_userName.getText().toString().getBytes("gbk").length < 4
							| et_userName.getText().toString().getBytes("gbk").length > 16) {
						Toast.makeText(JddRegisterActivity.this, R.string.chinese_characters_numbers_and_letters,
								Toast.LENGTH_SHORT).show();
					} else if (et_userPassword.getText().toString().length() < 6
							| et_userPassword.getText().toString().length() > 15) {
						Toast.makeText(JddRegisterActivity.this, R.string.enter_the_password_for_six_to_fifteen,
								Toast.LENGTH_SHORT).show();
					} else if (et_userPassword.getText().toString().length() != (et_userPassword.getText().toString()
							.replace(" ", "").length())) {
						Toast.makeText(JddRegisterActivity.this, R.string.not_contain_spaces, Toast.LENGTH_SHORT)
								.show();
					} else {
						AsyncLoader task = new AsyncLoader();
						task.execute("100");
						// //直接模拟成功
						// ApplicationData.getInstance().setUserName(et_userName.getText().toString());
						// ApplicationData.getInstance().setUserPassword(et_userPassword.getText().toString());
						// ApplicationData.getInstance().setUserID("12345678");
						// Intent intent = new Intent(JddRegisterActivity.this,
						// JddRegisterSucessActivity.class);
						// startActivity(intent);
						// finish();
					}
				} catch (Exception e) {
					// TODO: handle exception
					// e.printStackTrace();
				}
			}
		});

		tv_anoucement.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				startActivityForResult(new Intent(JddRegisterActivity.this, AnnouncementActivity.class), 0);
			}
		});

	}

	public class AsyncLoader extends AsyncTask<String, Integer, String> {// 继承AsyncTask

		// 1.准备运行
		protected void onPreExecute() {
			showdialog.showDialog(JddRegisterActivity.this);
		}

		// 2.正在后台运行
		@Override
		protected String doInBackground(String... params) {
			String strResult;
			try {
				userName = et_userName.getText().toString();
				userPwd = et_userPassword.getText().toString();
				String cmdName = et_user_cmdName.getText().toString().trim();
				JSONObject param = new JSONObject();
				param.put("Name", userName);
				param.put("CmdName", cmdName);
				param.put("Pw", userPwd);// Password
				// 推广联盟ID
				param.put("CmdID", ApplicationData.getInstance().getCommenderID());// CommenderID
																					// AppVersionConfig.CommenderID
				String action = params[0];
				// 获取请求返回值
				strResult = GetRequestParams.getRequestResult(param.toString(), action, getApplicationContext());
				return strResult;
			} catch (Exception e) {
				// TODO: handle exception
				Log.e("error", e.toString());
				return null;
			}
		}

		// 3.进度更新
		protected void onProgressUpdate(Integer... progress) {
		}

		// 4.完成后台任务
		protected void onPostExecute(String result) {
			if (result != null) {
				try {
					JSONTokener jsonParser = new JSONTokener(result);
					JSONObject js = (JSONObject) jsonParser.nextValue();
					// 接下来的就是JSON对象的操作了
					if (Integer.parseInt(js.getString("Code")) == 0) {
						// Intent intent = new Intent();
						// intent.putExtra("userName", userName);
						// intent.putExtra("userPwd", userPwd);
						// setResult(RESULT_OK,intent);
						// finish();
						// Intent intent = new Intent();
						// intent.setClass(RegisteredActivity.this,
						// LoginActivity.class);
						// startActivity(intent);
						loginAsyncLoader logtask = new loginAsyncLoader();
						logtask.execute("101");
					}
					Toast.makeText(JddRegisterActivity.this, js.getString("Data"), Toast.LENGTH_SHORT).show();
				} catch (JSONException ex) {
					// 异常处理代码
					Log.e("error", ex.toString());
				} finally {
					showdialog.closeDialog();
				}
			} else {
				Toast.makeText(JddRegisterActivity.this, getString(R.string.problem_01), Toast.LENGTH_LONG).show();
			}
		}

		// 5.完成后操作
		protected void onCancelled() {
		}

	}

	public void onResume() {
		super.onResume();
		
	}

	public void onPause() {
		super.onPause();
		
	}

	/**
	 * 登录以获取及保存userid
	 * 
	 * @author jddr
	 * 
	 */
	public class loginAsyncLoader extends AsyncTask<String, Integer, String> {// 继承AsyncTask

		// 1.准备运行
		protected void onPreExecute() {
			// showdialog.showDialog(JddRegisterActivity.this);
		}

		// 2.正在后台运行
		@Override
		protected String doInBackground(String... params) {
			String strResult;
			try {
				userName = et_userName.getText().toString();
				userPwd = et_userPassword.getText().toString();
				// 设置请求所需参数
				JSONObject param = new JSONObject();
				param.put("Name", userName);
				param.put("Pw", userPwd);// Password
				String action = params[0];
				// 获取请求返回值
				strResult = GetRequestParams.getRequestResult(param.toString(), action, getApplicationContext());
				return strResult;
			} catch (Exception e) {
				// TODO: handle exception
				Log.e("error", e.toString());
				return null;
			}
		}

		// 3.进度更新
		protected void onProgressUpdate(Integer... progress) {
		}

		// 4.完成后台任务
		protected void onPostExecute(String result) {
			if (result != null) {
				try {
					JSONTokener jsonParser = new JSONTokener(result);
					JSONObject js = (JSONObject) jsonParser.nextValue();
					// 接下来的就是JSON对象的操作了
					if (Integer.parseInt(js.getString("Code")) == 0) {
						// 保存登录时返回的userId进全局变量
						// app.setUserID(js.getString("Data"));
						// MyPreference.getInstance(JddRegisterActivity.this).setUserId(app.getUserID());
						// String UserID = app.getUserID();
						// Log.d("LoginActivity", "保存全局变量UserID= "+UserID);
						// 跳转
						// setResult(RESULT_OK);
						// // 销毁本页面
						// JddRegisterActivity.this.finish();

						// 保存用户登录信息
						Editor edit = sp.edit();
						edit.putString(et_userName.getText().toString(), et_userPassword.getText().toString());
						edit.putString("last-user", et_userName.getText().toString());
						edit.commit();

						ApplicationData.getInstance().setUserName(et_userName.getText().toString());
						ApplicationData.getInstance().setUserPassword(et_userPassword.getText().toString());
						ApplicationData.getInstance().setUserID(js.getString("Data"));

						if(!RegisterWay.equals("1"))
						{
					        setResult(RESULT_OK);						
						    EventManager.getInstance().onEvent(EventType.EV_BLL_UI_MAIN_LOT_REFRESH, null);
                            finish();
						}else
						{
							EventManager.getInstance().onEvent(EventType.EV_BLL_UI_MAIN_LOT_REFRESH, null);
							Intent intent = new Intent(JddRegisterActivity.this, JddRegisterSucessActivity.class);
							startActivityForResult(intent, REQ_REGISTER_FROM_HOMEFRM);
						}
						//Intent intent = new Intent(JddRegisterActivity.this, JddRegisterSucessActivity.class);
						//startActivityForResult(intent, REQ_REGISTER_FROM_HOMEFRM);
					    
					} else {
						Toast.makeText(JddRegisterActivity.this, js.getString("Data"), Toast.LENGTH_SHORT).show();
					}
				} catch (JSONException ex) {
					// 异常处理代码
					Log.e("error", ex.toString());
				} finally {
					// showdialog.closeDialog();
				}
			} else {
				Toast.makeText(JddRegisterActivity.this, getString(R.string.problem_01), Toast.LENGTH_LONG).show();
			}
		}

		// 5.完成后操作
		protected void onCancelled() {
		}

	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			setResult(RESULT_CANCELED);
			this.finish();
			return true;
		} else {
			return super.onKeyDown(keyCode, event);
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == REQ_REGISTER_FROM_HOMEFRM) {
			if (resultCode == RESULT_OK) {
				setResult(RESULT_OK, data);
			}
		}
		finish();
	};

}
